package com.xgsm.springsecurityauthdemo.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xgsm.springsecurityauthdemo.Mapper.MenuMapper;
import com.xgsm.springsecurityauthdemo.Mapper.UserMapper;
import com.xgsm.springsecurityauthdemo.domain.User;
import com.xgsm.springsecurityauthdemo.domain.UserLogin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    MenuMapper menuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//       1、根据用户名获取数据中的系统用户
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//        从数据库中查询到的User::getUserName，和方法中的name要一致
        lambdaQueryWrapper.eq(User::getUserName, username);//查询条件
        User user = userMapper.selectOne(lambdaQueryWrapper);
        if (Objects.isNull(user)){
            throw  new RuntimeException("用户名错误!");
        }
        // 2、 TODD 查询权限信息
        List<String> authList = menuMapper.selectPermsByUserId(user.getId());
        // 3、返回UserDetails
        return new UserLogin(user,authList);
    }
}
